from datetime import datetime, timedelta
from jose import JWTError, jwt
from app.core.config import settings
from sqlalchemy.orm import Session
import bcrypt
from sqlalchemy import Column


def verify_password(plain_password: str, hashed_password: str | Column[str]):
    return bcrypt.checkpw(plain_password.encode(), hashed_password.encode())


def get_password_hash(password: str):
    return bcrypt.hashpw(password.encode(), bcrypt.gensalt())


def create_access_token(data: dict, expires_delta: timedelta | None):
    to_encode = data.copy()
    if expires_delta is not None:
        expire = datetime.now() + expires_delta
    else:
        expire = datetime.now() + timedelta(minutes=15)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(
        to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM
    )
    return encoded_jwt


def authenticate_user(db: Session, username: str, password: str):
    from app.crud import crud

    user = crud.get_user_by_username(db, username)
    if not user or not verify_password(password, user.password_hash):
        return None
    return user


blacklisted_tokens = set()


def invalidate_token(token: str):
    """将Token加入黑名单"""
    blacklisted_tokens.add(token)


def verify_token(token: str):
    """验证Token"""
    return not token in blacklisted_tokens
